package com.orangelife.mobile.main.activity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.bonree.agent.android.harvest.Statistics;
import com.common.sp.AppSp;
import com.common.sp.CommSp2;
import com.common.sp.OtherSp;
import com.common.sp.UserSp;
import com.common.update.UpdateBiz;
import com.curry.android.util.ScreenUtil;
import com.curry.android.util.StringUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.app.service.MyService;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.main.biz.JumpUtil;
import com.orangelife.mobile.main.fragment.Page1Fragment;
import com.orangelife.mobile.main.fragment.Page4Fragment;
import com.orangelife.mobile.surrounding.fragment.SurroundingMerchantFragment;
import com.orangelife.mobile.tehui.TeHuiFragment2;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.util.LogE;
import com.orangelife.mobile.util.ToastHelper;

/**
 * 功能描述：自定义TabHost,APP主界面框架
 * <p/>
 * Create by ChenXiang.Modify by wgf on 160429
 *
 * @author cx
 */
public class MainTablActivity extends FragmentActivity {

    //定义FragmentTabHost对象
    public FragmentTabHost mTabHost;
    //定义一个布局
    private LayoutInflater layoutInflater;
    /**
     * Tab选项卡的文字
     */
    private String mTextviewArray[] = {"管家", "发现", "周边", "我的"};
    /**
     * 对应底部四个按钮的四个Fragment界面
     */
    private Class fragmentArray[] = {Page1Fragment.class, TeHuiFragment2.class, SurroundingMerchantFragment.class, Page4Fragment.class};
    /**
     * 定义数组来存放按钮图片
     */
    private int mImageViewArray[] = {R.drawable.tab_guanjia_btn, R.drawable.tab_discovery_btn, R.drawable.tab_nearby_btn,
            R.drawable.tab_my_btn};

    private boolean isFromJPush;
    private boolean hasLoadADImg = false;
    private MyService.MyBinder myBinder;
    private boolean isBound;
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MyService.MyBinder) service;
            if (CurryApplication.getInstance().isUpdate() && Constant.FIRST_OPEN.equals("0")) {
                Constant.FIRST_OPEN = "1";
                UpdateBiz.requestUpdateVersion(myBinder, MainTablActivity.this, 2);
            }

            String currCommID = CommSp2.getCommID();
            String preCommID = OtherSp.getLastCommID();
            if (!hasLoadADImg && !currCommID.equals(preCommID)) {    //setHeader完成并且切换过小区时,加载当前小区的闪屏广告.
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        hasLoadADImg = true;
                        myBinder.loadADImage();
                    }
                }).start();

            }
        }
    };


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_tab_layout);
        CurryApplication.getInstance().addActivity(this);
        isFromJPush = false;
        bindService();
        getIntentInfo();
        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
//        LogE.E(MainTablActivity.class.getSimpleName(), "onResume()");
        showSignInDot();
        setHeader();
        showFirstGuideView();
        String currCommID = CommSp2.getCommID();
        String preCommID = OtherSp.getLastCommID();
        if (!hasLoadADImg && !currCommID.equals(preCommID)) {    //setHeader完成并且切换过小区时,加载当前小区的闪屏广告.
            bindService();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void bindService() {
        Intent intent = new Intent(MainTablActivity.this, MyService.class);
        isBound = bindService(intent, connection, BIND_AUTO_CREATE);
    }


    private void setHeader() {
        CurryApplication.getInstance().setAccessToken();/*必须重新设置token，如果程序被杀死，存在HttpUtil中的token变量也会被清空*/
        CurryApplication.getInstance().setCommID(this, isFromJPush);

        isFromJPush = false;
    }

    private void getIntentInfo() {
        String webViewUrl = getIntent().getStringExtra("WebViewUrl");
        if (!StringUtil.isBlank(webViewUrl)) {
            isFromJPush = true;
            JumpUtil.jumpActivity(this, webViewUrl);
        }
    }

    private void initView() {
        //实例化布局对象
        layoutInflater = LayoutInflater.from(this);
        //实例化TabHost对象，得到TabHost
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        //得到fragment的个数
        int count = fragmentArray.length;
        for (int i = 0; i < count; i++) {
            //为每一个Tab按钮设置图标、文字和内容
            TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
            //将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
            //设置Tab按钮的背景
            //amTabHost.getTabWidget().getChildAt(i).setBackgroundResource();
        }
        mTabHost.setOnTabChangedListener(tabChangeListener);
//        UserInfoSp.setSignInDate("");
    }

    TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener() {

        @Override
        public void onTabChanged(String tabId) {
            if ("发现".equals(tabId)) {
                showSecondGuideView();
                showSignInDot();
            }
        }
    };

    /**
     * 如果今天尚未签到，则显示红点
     */
    private void showSignInDot() {
        //设置Tab按钮的背景
        View v = mTabHost.getTabWidget().getChildAt(1);
        LinearLayout ll_item_view = (LinearLayout) v.findViewById(R.id.ll_item_view);
        LinearLayout ll_item = (LinearLayout) ll_item_view.findViewById(R.id.ll_item);
        if (UserSp.hasSign()) {
            ll_item.setBackgroundResource(0);
        } else {
            ll_item.setBackgroundResource(R.drawable.red_bg_dot);
        }
    }

    /**
     * 给Tab按钮设置图标和文字
     */
    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_view, null);

        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageViewArray[index]);

        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTextviewArray[index]);

        return view;
    }

    /*____________________引导层代码start______________________*/

    int guideStep;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean canTouch;
        if (!AppSp.isShowGuide()) {
            guideStep = 0;
        }
        if (guideStep == 1) {
            canTouch = isFirstTouchArea(ev);
        } else if (guideStep == 2) {
            canTouch = isSecondTouchArea(ev);
        } else {
            canTouch = true;
        }
        if (canTouch) {
            return super.dispatchTouchEvent(ev);
        } else {
            return false;
        }
    }

    private boolean isFirstTouchArea(MotionEvent ev) {
        int bottomBarHeight = 0;
        if (mTabHost != null) {
            bottomBarHeight = mTabHost.getHeight();
        }
        int screenHeight = ScreenUtil.getScreenHeight(this);
        int screenWidth = ScreenUtil.getScreenWidth(this);
        if (bottomBarHeight == 0) {
            bottomBarHeight = screenHeight;
        }
        int touchAreaHeight = ScreenUtil.getScreenHeight(this) - bottomBarHeight;
        return (ev.getX() > screenWidth / 4 && ev.getX() < screenWidth / 2 && ev.getY() > touchAreaHeight && ev.getY() < screenHeight);
    }

    private boolean isSecondTouchArea(MotionEvent ev) {
        int topBarHeight = ScreenUtil.dip2px(this, 70);
        if (ev.getY() > 0 && ev.getY() < topBarHeight) {
            return true;
        } else {
            return false;
        }
    }

    ImageView ivGuide;
    ImageView ivFill;
    ViewGroup content;

    private void hideFirstGuideView() {
        if (ivGuide != null && ivFill != null) {
            ivGuide.setVisibility(View.GONE);
            ivFill.setVisibility(View.GONE);
            ivGuide.destroyDrawingCache();
            ivFill.destroyDrawingCache();
            ivGuide = null;
            ivFill = null;
        }
    }

    private void showFirstGuideView() {
        content = (ViewGroup) this.findViewById(android.R.id.content);
        if (!AppSp.isShowGuide()) {
            hideFirstGuideView();
            return;
        }
        if (guideStep == 2) {
            return;
        }
        if (ivFill == null && ivGuide == null) {
            guideStep = 1;
            LinearLayout container = new LinearLayout(this);
            container.setGravity(Gravity.BOTTOM);
            container.setOrientation(LinearLayout.HORIZONTAL);
            container.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            ivFill = new ImageView(this);
            int width = ScreenUtil.getScreenWidth(this);
            int left = width / 4;
            float i = 111 * (width / (float) 1080);
            LinearLayout.LayoutParams paramsFill = new LinearLayout.LayoutParams((int) (left + left / 2 - i), ViewGroup.LayoutParams.MATCH_PARENT);
            ivFill.setLayoutParams(paramsFill);
            ivFill.setBackgroundResource(R.drawable.sign_guide_fill);
            ivGuide = new ImageView(this);
            LinearLayout.LayoutParams paramGuide = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            ivGuide.setLayoutParams(paramGuide);
            // TODO: 2016-11-22 签到功能:暂时把图片移除掉,因为没有用,图片存在coding上;
            //ivGuide.setBackgroundResource(R.drawable.sign_guide1);
            container.addView(ivFill);
            container.addView(ivGuide);
            content.addView(container);
        }
    }

    private void showSecondGuideView() {
        if (AppSp.isShowGuide() && ivGuide != null) {
            guideStep = 2;
            // TODO: 2016-11-22 签到功能:暂时把图片移除掉,因为没有用,图片存在coding上;
            //ivGuide.setBackgroundResource(R.drawable.sign_guide2);
        }
    }

     /*__________引导层代码end____________*/


    /*__________重载返回键start____________*/

    /**
     * 重载返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 双击退出
     */
    private boolean isExit;
    @SuppressLint("HandlerLeak")
    Handler mHandler2 = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }

    };

    /**
     * 双击退出的方法体
     */
    public void exit() {
        if (!isExit) {
            isExit = true;
            ToastHelper.getInstance()._toast(
                    getResources().getString(
                            R.string.again_according_to_exit_the_program));
            mHandler2.sendEmptyMessageDelayed(0, 2000);
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            CurryApplication.getInstance().exit();
            this.finish();
        }
        BLog.getInstance().upload();
    }

     /*__________重载返回键end____________*/

    @Override
    protected void onDestroy() {
        if (isBound) {
            unbindService(connection);
        }
        super.onDestroy();
        BLog.getInstance().upload();
    }
}
